package com.tencreat.service.mall.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencreat.common.constant.Lock4jConstant;
import com.tencreat.common.constant.MallConstants;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.BaseEntity;
import com.tencreat.common.core.domain.OrderVO;
import com.tencreat.common.core.domain.entity.SysDictData;
import com.tencreat.common.core.domain.entity.SysUser;
import com.tencreat.common.core.domain.model.*;
import com.tencreat.common.enums.*;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.*;
import com.tencreat.domain.account.MallStore;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.mall.vo.TotalOrderStatisticsVO;
import com.tencreat.domain.mall.*;
import com.tencreat.domain.mall.dto.*;
import com.tencreat.domain.mall.vo.*;
import com.tencreat.mapper.mall.GoodsRollOrderMapper;
import com.tencreat.mapper.mall.MallOrderMapper;
import com.tencreat.service.account.IMallStoreService;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.account.IStoreWithdrawAuditService;
import com.tencreat.service.account.ISupplierWithdrawAuditService;
import com.tencreat.service.mall.*;
import com.tencreat.service.system.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 商城订单Service业务层处理
 *
 * @author tencreat
 * @date 2021-08-13
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class MallOrderServiceImpl extends ServiceImpl<MallOrderMapper, MallOrder> implements IMallOrderService {


    private final IMallAddressService mallAddressService;
    private final IMallGoodsService mallGoodsService;

    @Autowired
    private IMallOrderGoodsService mallOrderGoodsService;
    private final IMallCouponUserService mallCouponUserService;
    private final IMallCouponService mallCouponService;
    private final IMallUserService mallUserService;
    private final IMallGoodsNormsService mallGoodsNormsService;
    private final IMallMessageInformService mallMessageInformService;
    private final RabbitSendUtils rabbitUtils;
    private final IBalanceChangeService balanceChangeService;

    @Autowired
    private IMallCategoryService mallCategoryService;

    @Autowired
    private IMallStoreService mallStoreService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISupplierWithdrawAuditService supplierWithdrawAuditService;
    @Autowired
    private IStoreWithdrawAuditService storeWithdrawAuditService;

    @Autowired
    private IRechargeOrderService rechargeOrderService;

    @Autowired
    private GoodsRollOrderMapper goodsRollOrderMapper;


    @Override
    public MallOrder selectMallOrderById(ReqIdParam id) {
        return baseMapper.selectById(id.getId());
    }

    @Override
    public List<MallOrder> selectMallOrderList(MallOrder mallOrder) {
        return baseMapper.selectList(Wrappers.query(mallOrder));
    }

    @Override
    public int insertMallOrder(MallOrder mallOrder) {
        mallOrder.setCreateTime(LocalDateTime.now());
        return baseMapper.insert(mallOrder);
    }

    @Override
    public int updateMallOrder(MallOrder mallOrder) {
        mallOrder.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(mallOrder);
    }

    @Override
    public int deleteMallOrderByIds(ReqIdsParam ids) {

        return baseMapper.deleteBatchIds(ids.getId());
    }

    @Override
    public int deleteMallOrderById(ReqIdParam id) {
        return baseMapper.deleteById(id.getId());
    }

    @Override
    public HttpResult<IPage<ResOrderGoodsVO>> orderList(IdAndPage idParam, LoginUser loginUser) {
        Long uuid = loginUser.getAccountLogin().getUuid();
        Page<ResOrderGoodsVO> resOrderGoodsIPage = new Page<>(idParam.getPageNum(), idParam.getPageSize());

        Page<ResOrderGoodsVO> orderList = baseMapper.getOrderList(resOrderGoodsIPage, idParam.getId(), uuid);
        orderList.getRecords().forEach(item -> {
            if (item.getStoreId() != null && item.getStoreId() != 0L) {
                MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getId, item.getStoreId()).one();
                item.setStoreName(mallStore.getStoreName());
            }
        });

        return HttpResult.ok(orderList);
    }

    @Override
    public HttpResult<ResOrderGoodsVO> orderInfo(ReqIdParam idParam, LoginUser loginUser) {
        ResOrderGoodsVO orderInfo = baseMapper.getOrderInfo(idParam, loginUser.getAccountLogin().getUuid());
        if (orderInfo != null) {
            // 退货地址
            if (orderInfo.getAddressId() != null) {
                IMallDeliverAddressService mallDeliverAddressService = SpringUtil.getBean(IMallDeliverAddressService.class);
                MallDeliverAddress deliverAddress = mallDeliverAddressService.lambdaQuery().eq(MallDeliverAddress::getId, orderInfo.getAddressId())
                        .select(MallDeliverAddress::getName, MallDeliverAddress::getTel, MallDeliverAddress::getId).one();
                orderInfo.setRefundAddress(mallDeliverAddressService.refundAddress(orderInfo.getAddressId()));
                orderInfo.setRefundName(deliverAddress.getName());
                orderInfo.setRefundPhone(deliverAddress.getTel());
            }
            if (!orderInfo.getOrderType().equals(OrderType.SHOP)) {
                if (orderInfo.getStoreId() != 0L) {
                    MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getId, orderInfo.getStoreId()).one();
                    if (orderInfo.getVerificationOrder() == 1) {
                        orderInfo.setGoodUrl(mallStore.getPhoto());
//                        orderInfo.setStoreType(mallStore.getClassify());
                    }
                }
            }
        }

        return HttpResult.ok(orderInfo);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized HttpResult<ResOrderMallSubmitVO> submit(OrderMallSubmitDTO param, LoginUser loginUser) {
        //消息队列时长 分钟
        Long min = 30L;
        Long uuid = loginUser.getAccountLogin().getUuid();
        if (uuid == null) {
            throw new CustomException("uuid不能为空");
        }
        // 校验参数信息
        //checkData(param);

        //商品订单
        List<MallOrderGoods> orderGoodsList = new ArrayList<>();
        //总金额
        BigDecimal priceSum = new BigDecimal("0.00");
        //实付金额
        BigDecimal payPriceSum = new BigDecimal("0.00");
        //邮费
        BigDecimal postageSum = new BigDecimal("0.00");
        //
        BigDecimal couponPrice = new BigDecimal("0.00");

        MallCoupon coupon = null;

        //订单编号
        String orderSn = TenCreatUtil.getOrderNo();


        //用户ID
        MallUser mallUser = mallUserService.lambdaQuery().eq(MallUser::getUuid, uuid).one();
        //商品增加销量
        List<MallGoods> goodList = new ArrayList<>();
        //规格减库存
        List<MallGoodsNorms> goodsNormsList = new ArrayList<>();
        //订单
        MallOrder mallOrder = new MallOrder();
        mallOrder.setOrderSn(orderSn);

        if (param.getVoucherId() != null) {
            coupon = mallCouponService.getById(param.getVoucherId());
            couponPrice = coupon.getDiscount();
        }
        BigDecimal memberTotal = new BigDecimal("0.00");
        // 抵扣金额
        BigDecimal deductPrice = new BigDecimal("0.00");
        //快递地址
        MallAddress mallAddress = null;
        if (param.getAddressId() != null && (param.getOrderType().equals(OrderType.SHOP) && Objects.equals(param.getType(), "1"))) {
            mallAddress = mallAddressService.getById(param.getAddressId());
            mallOrder.setConsignee(mallAddress.getName());
            mallOrder.setMobile(mallAddress.getTel());
            mallOrder.setAddress(mallAddress.getProvinceName() + mallAddress.getCityName() + mallAddress.getCountyName()
                    + mallAddress.getAddressDetail());
            mallOrder.setAddressId(mallAddress.getId());
        }

        int count = 1;

        if (param.getOrderType().compareTo(OrderType.SHOP) == 0) {

            for (ResOrderMallGoodsVO goodPo : param.getGoods()) {
                //增加订单商品表
                MallOrderGoods item = new MallOrderGoods();
                item.setOrderStatus(OrderStatus.PAY);
                BigDecimal age = new BigDecimal("0.00");
                BigDecimal price = new BigDecimal("0.00");
                BigDecimal payPrice = new BigDecimal("0.00");
                BigDecimal memberPrice = new BigDecimal("0.00");
                MallGoods goods = mallGoodsService.getById(goodPo.getGoodsId());
                MallGoodsNorms goodsNorms = mallGoodsNormsService.getById(goodPo.getGoodsSpecId());
                //商城商品根据规格库存进行判断
                if (param.getOrderType().compareTo(OrderType.SHOP) == 0) {
                    if (goodsNorms != null && goodsNorms.getInventory() <= 0 || goodsNorms.getInventory() < goodPo.getGoodsNum()) {
                        throw new CustomException("库存不足购买失败");
                    }
                    //增加销量 减少库存
                    goods.setCommoditySales(goods.getCommoditySales() == null ? 1 : goods.getCommoditySales() + 1);
                    goods.setInventory(goods.getInventory() - goodPo.getGoodsNum());
                }
                //存放 等待一次性修改
                goodList.add(goods);
                //快递运输才需要运费
                if (MallConstants.MALL_LOGISTICS_POST.longValue() == goods.getLogisticsId().longValue()) {
                    age = mallAddressService.getPostAgeByGood(goodPo.getGoodsId(), param.getAddressId());
                    age = age == null ? BigDecimal.ZERO : age;
                }
                goodsNorms.setInventory(goodsNorms.getInventory() - goodPo.getGoodsNum());
                //判断商品
                price = goodsNorms.getRetailPrice().multiply(new BigDecimal(goodPo.getGoodsNum()));
                payPrice = goodsNorms.getRetailPrice().multiply(new BigDecimal(goodPo.getGoodsNum()));
                deductPrice = deductPrice.add(goodsNorms.getDeductPrice());
                goodsNormsList.add(goodsNorms);

                //优惠券
                BigDecimal multiply = new BigDecimal("0.00");
                if (null != param.getPriceTotal()) {
                    multiply = couponPrice.multiply(payPrice.divide(param.getPriceTotal(), 3, BigDecimal.ROUND_HALF_UP));
                    if (coupon != null) {
                        item.setCouponId(coupon.getId());//优惠券id
                    }
                }
                if (mallAddress != null) {
                    item.setConsignee(mallAddress.getName());
                    item.setMobile(mallAddress.getTel());
                    item.setAddress(mallAddress.getProvinceName() + mallAddress.getCityName() + mallAddress.getCountyName()
                            + mallAddress.getAddressDetail());
                    item.setReceiptAddressId(mallAddress.getId());
                }
                item.setOrderSn(orderSn);
                item.setOrderGoodsSn(orderSn + "-" + count);
                item.setGoodsId(goodPo.getGoodsId());
                item.setNormsId(Long.valueOf(goodPo.getGoodsSpecId()));
                item.setGoodsName(goods.getName());
                item.setGoodsSn(goods.getGoodsSn());
                item.setPostage(age);
                item.setPayPrice(payPrice.subtract(multiply));
                item.setPrice(price);
                item.setCouponPrice(multiply);
                item.setNumber(goodPo.getGoodsNum());
                item.setPicUrl(goodsNorms.getPicUrl());
                item.setComment(0L);
                item.setDelFlag("0");
                item.setUuid(uuid);
                item.setOrderType(param.getOrderType());
                item.setUpdateTime(LocalDateTime.now());
                item.setCreateTime(LocalDateTime.now());
                orderGoodsList.add(item);
                //费用汇总
                postageSum = postageSum.add(age);
                payPriceSum = payPriceSum.add(payPrice);
                priceSum = priceSum.add(price);
                // 数量+1
                count++;
                mallOrder.setUserId(goods.getUserId());
            }
        }

        if (param.getOrderType().compareTo(OrderType.STORE) == 0) {
            for (ResOrderMallGoodsVO good : param.getGoods()) {
                if (good.getGoodsNum() != 0) {
                    MallGoods goods = mallGoodsService.getById(good.getGoodsId());
                    //店铺商品直接根据商品表中的库存进行判断
                    if (goods != null && goods.getInventory() <= 0 || goods.getInventory() < good.getGoodsNum()) {
                        throw new CustomException("库存不足购买失败");
                    }
                    for (int i = 0; i < good.getGoodsNum(); i++) {
                        //获取核销码
                        String verificationCode = TenCreatUtil.getRandomNumCode(6);
                        //增加订单商品表
                        MallOrderGoods item = new MallOrderGoods();
                        item.setOrderStatus(OrderStatus.PAY);
                        BigDecimal age = new BigDecimal("0.00");
                        BigDecimal price = new BigDecimal("0.00");
                        BigDecimal payPrice = new BigDecimal("0.00");
                        //增加销量 减少库存
                        goods.setCommoditySales(goods.getCommoditySales() == null ? 1 : goods.getCommoditySales() + 1);
                        goods.setInventory(goods.getInventory() - 1);
                        //存放 等待一次性修改
                        goodList.add(goods);
                        item.setOrderSn(orderSn);
                        item.setOrderGoodsSn(orderSn + "-" + count);
                        item.setGoodsId(good.getGoodsId());
                        item.setNormsId(Long.valueOf(good.getGoodsSpecId()));
                        item.setGoodsName(goods.getName());
                        item.setGoodsSn(goods.getGoodsSn());
                        item.setPayPrice(goods.getRetailPrice());
                        item.setPrice(goods.getRetailPrice());
                        item.setNumber(1);
                        item.setPicUrl(goods.getPicUrl());
                        item.setVerificationCode(verificationCode);
                        item.setVerificationOrder(0);
                        item.setComment(0L);
                        item.setDelFlag("0");
                        item.setUuid(uuid);
                        item.setOrderType(param.getOrderType());
                        item.setUpdateTime(LocalDateTime.now());
                        item.setCreateTime(LocalDateTime.now());
                        orderGoodsList.add(item);
                        //费用汇总
                        payPriceSum = payPriceSum.add(goods.getRetailPrice());
                        priceSum = priceSum.add(goods.getRetailPrice());
                        // 数量+1
                        count++;
                        mallOrder.setStoreId(goods.getStoreId());
                        mallOrder.setUserId(goods.getUserId());
                    }
//                    mallOrder.setGoodsPrice(goods.getRetailPrice().multiply(new BigDecimal(good.getGoodsNum())));
                }
            }
            mallOrder.setVerificationOrder(MallConstants.MALL_FALSE);


        }

        mallOrder.setUuid(uuid);
        mallOrder.setOrderSn(orderSn);
        mallOrder.setOrderType(param.getOrderType());
        mallOrder.setStatusShop(ShopOrderStatus.PAY);
        mallOrder.setOrderStatus(OrderStatus.PAY);
        mallOrder.setStatusUser(UserOrderStatus.WAIT_PAY);

        BigDecimal decimal = payPriceSum.add(postageSum).subtract(couponPrice);
        if (decimal.doubleValue() <= 0) {
            throw new CustomException("支付金额需大于0");
        }
        //设置配送费
        mallOrder.setFreightPrice(postageSum);
        //mallOrder.setGoodsId(param.getGoods().get(0).getGoodsId());
        mallOrder.setAftersaleStatus(0);
        mallOrder.setMessage(param.getRemark());
        mallOrder.setGoodsPrice(priceSum);
        //mallOrder.setGrouponPrice(new BigDecimal("0.00"));
        mallOrder.setDelFlag("0");
        mallOrder.setCreateTime(LocalDateTime.now());
        mallOrder.setUpdateTime(LocalDateTime.now());
        mallOrder.setMessage(param.getRemark());
        mallOrder.setActualPrice(decimal);
        mallOrder.setOrderPrice(priceSum);
        mallOrder.setCouponPrice(couponPrice);
        //mallOrder.setMemberPrice(memberTotal);
        mallOrder.setEndTime(LocalDateTime.now().plusMinutes(min));
        //优惠券使用
        if (coupon != null) {
            mallOrder.setCouponId(coupon.getId());
            mallCouponUserService.updateState(coupon.getId(), uuid, AllEnum.couponType.USED.getType());
        }

        //订单10分钟未支付 取消
        sendDelayMessageCancelOrder(new OrderVO(mallOrder.getOrderSn(), mallOrder.getOrderType()), min);

        save(mallOrder);
        mallOrderGoodsService.saveBatch(orderGoodsList);
        mallGoodsService.updateBatchById(goodList);
        mallGoodsNormsService.updateBatchById(goodsNormsList);
        return HttpResult.ok(new ResOrderMallSubmitVO(orderSn, decimal));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized HttpResult<ResOrderMallSubmitVO> submitMember(OrderMallSubmitDTO param, LoginUser loginUser) {
        //消息队列时长 分钟
        Long min = 30L;
//        Long uuid = loginUser.getAccountLogin() == null ? param.getAutoPtUuid() : loginUser.getAccountLogin().getUuid();
        Long uuid = loginUser.getAccountLogin().getUuid();
        if (uuid == null) {
            throw new CustomException("uuid不能为空");
        }
        //商品订单
        List<MallOrderGoods> orderGoodsList = new ArrayList<>();
        //总金额
        BigDecimal priceSum = new BigDecimal("0.00");
        //实付金额
        BigDecimal payPriceSum = new BigDecimal("0.00");
        //订单编号
        String orderSn = TenCreatUtil.getOrderNo();
        //商品增加销量
        List<MallGoods> goodList = new ArrayList<>();
        //规格减库存
        List<MallGoodsNorms> goodsNormsList = new ArrayList<>();
        //订单
        MallOrder mallOrder = new MallOrder();
        mallOrder.setOrderSn(orderSn);
        for (ResOrderMallGoodsVO goodPo : param.getGoods()) {
            //增加订单商品表
            MallOrderGoods item = new MallOrderGoods();
            item.setOrderStatus(OrderStatus.PAY);
            BigDecimal age = new BigDecimal("0.00");
            BigDecimal price = new BigDecimal("0.00");
            BigDecimal payPrice = new BigDecimal("0.00");
            MallGoods goods = mallGoodsService.getById(goodPo.getGoodsId());
            MallGoodsNorms goodsNorms = mallGoodsNormsService.getById(goodPo.getGoodsSpecId());
            if (goodsNorms.getInventory() <= 0 || goodsNorms.getInventory() < goodPo.getGoodsNum()) {
                throw new CustomException("库//订单10分钟未支付 取消存不足购买失败");
            }
            //增加销量 减少库存
            goods.setCommoditySales(goods.getCommoditySales() == null ? 1 : goods.getCommoditySales() + 1);
            goods.setInventory(goods.getInventory() - goodPo.getGoodsNum());
            goodsNorms.setInventory(goodsNorms.getInventory() - goodPo.getGoodsNum());
            //存放 等待一次性修改
            goodList.add(goods);
            goodsNormsList.add(goodsNorms);
/*            //开通会员
            if (param.getOrderType().compareTo(OrderType.MEMBER) == 0) {
                //判断商品
                price = goodsNorms.getRetailPrice();
                payPrice = goodsNorms.getRetailPrice();
            }*/
            item.setOrderSn(orderSn);
            item.setOrderGoodsSn(orderSn + "-" + 1);
            item.setGoodsId(goodPo.getGoodsId());
            item.setNormsId(Long.valueOf(goodPo.getGoodsSpecId()));
            item.setGoodsName(goods.getName());
            item.setGoodsSn(goods.getGoodsSn());
            item.setPostage(age);
            item.setPayPrice(payPrice.subtract(BigDecimal.ZERO));
            item.setPrice(price);
            item.setCouponPrice(BigDecimal.ZERO);
            item.setNumber(goodPo.getGoodsNum());
            item.setPicUrl(goodsNorms.getPicUrl());
            item.setComment(0L);
            item.setDelFlag("0");
            item.setUuid(uuid);
            item.setOrderType(param.getOrderType());
            item.setUpdateTime(LocalDateTime.now());
            item.setCreateTime(LocalDateTime.now());
            // item.setMemberPrice(memberPrice);
            orderGoodsList.add(item);
            payPriceSum = payPriceSum.add(payPrice);
            priceSum = priceSum.add(price);
        }
        mallOrder.setUuid(uuid);
        mallOrder.setOrderSn(orderSn);
        mallOrder.setOrderType(param.getOrderType());
        mallOrder.setStatusShop(ShopOrderStatus.PAY);
        mallOrder.setOrderStatus(OrderStatus.PAY);
        mallOrder.setStatusUser(UserOrderStatus.WAIT_PAY);

        /*//开通会员
        if (param.getOrderType().getValue() == OrderType.MEMBER.getValue()) {
            mallOrder.setStatusShop(ShopOrderStatus.WAIT_RECEIVED);
        }
        mallOrder.setDeductPrice(BigDecimal.ZERO);*/
        //设置配送费
        mallOrder.setFreightPrice(BigDecimal.ZERO);
        //mallOrder.setGoodsId(param.getGoods().get(0).getGoodsId());
        mallOrder.setAftersaleStatus(0);
        mallOrder.setMessage(param.getRemark());
        mallOrder.setGoodsPrice(priceSum);
        //mallOrder.setGrouponPrice(new BigDecimal("0.00"));
        mallOrder.setDelFlag("0");
        mallOrder.setCreateTime(LocalDateTime.now());
        mallOrder.setUpdateTime(LocalDateTime.now());
        mallOrder.setMessage(param.getRemark());
        mallOrder.setActualPrice(payPriceSum);
        mallOrder.setOrderPrice(priceSum);
        mallOrder.setCouponPrice(BigDecimal.ZERO);
        //mallOrder.setMemberPrice(BigDecimal.ZERO);
        mallOrder.setEndTime(LocalDateTime.now().plusMinutes(min));

        //订单10分钟未支付 取消
        sendDelayMessageCancelOrder(new OrderVO(mallOrder.getOrderSn(), mallOrder.getOrderType()), min);

        save(mallOrder);
        mallOrderGoodsService.saveBatch(orderGoodsList);
        mallGoodsService.updateBatchById(goodList);
        mallGoodsNormsService.updateBatchById(goodsNormsList);
        return HttpResult.ok(new ResOrderMallSubmitVO(orderSn, priceSum));
    }


    @Override
    public HttpResult<ResOrderMallBudgetVO> budget(OrderMallBudgetDTO orderMallBudgetVO, LoginUser loginUser) {
        ResOrderMallBudgetVO resOrderMallBudget = new ResOrderMallBudgetVO();
        // 查询用户
        MallUser mallUser = mallUserService.lambdaQuery().eq(MallUser::getUuid, loginUser.getAccountLogin().getUuid()).one();
        if (mallUser == null || mallUser.getStatus() != 0) {
            throw new CustomException("用户信息有误");
        }
        List<ResOrderMallBudgetGoodsVO> goods = new ArrayList<>();
        // 商品总价
        BigDecimal priceTotal = new BigDecimal("0.00");
        BigDecimal postAgeTotal = new BigDecimal("0.00");

        // 会员优惠价格
        BigDecimal memberTotal = new BigDecimal("0.00");

        // 抵扣金额
        BigDecimal deductPrice = new BigDecimal("0.00");
        for (ResOrderMallGoodsVO good : orderMallBudgetVO.getGoods()) {
            BigDecimal payPrice = null;

            MallGoods mallGoods = mallGoodsService.getOne(new QueryWrapper<MallGoods>().eq("id", good.getGoodsId()));
            MallGoodsNorms mallGoodsNorms = mallGoodsNormsService.getOne(new QueryWrapper<MallGoodsNorms>().eq("id", good.getGoodsSpecId()).eq("goods_id", good.getGoodsId()));


            if (OrderType.SHOP.getValue() == orderMallBudgetVO.getOrderType().getValue()) {
                payPrice = mallGoodsNorms.getRetailPrice().multiply(new BigDecimal(good.getGoodsNum()));
                deductPrice = deductPrice.add(mallGoodsNorms.getDeductPrice());
            }

            if (OrderType.STORE.getValue() == orderMallBudgetVO.getOrderType().getValue()) {
                payPrice = mallGoods.getRetailPrice().multiply(new BigDecimal(good.getGoodsNum()));
            }

            priceTotal = priceTotal.add(payPrice);

            //快递价
            BigDecimal postAgePrice = BigDecimal.ZERO;
            if (MallConstants.MALL_LOGISTICS_POST.longValue() == mallGoods.getLogisticsId().longValue() && orderMallBudgetVO.getAddressId() != null) {
                postAgePrice = mallAddressService.getPostAgeByGood(good.getGoodsId(), orderMallBudgetVO.getAddressId());
                postAgePrice = postAgePrice == null ? BigDecimal.ZERO : postAgePrice;
                postAgeTotal = postAgeTotal.add(postAgePrice);
            }

            ResOrderMallBudgetGoodsVO resOrderMallBudgetGoods = new ResOrderMallBudgetGoodsVO();
            resOrderMallBudgetGoods.setGoodsId(good.getGoodsId().intValue());
            resOrderMallBudgetGoods.setGoodsNum(good.getGoodsNum());
            resOrderMallBudgetGoods.setProductId(good.getGoodsProductId());
            resOrderMallBudgetGoods.setGoodsSpecId(good.getGoodsSpecId());
            resOrderMallBudgetGoods.setGoodsName(mallGoods.getName());
            resOrderMallBudgetGoods.setGoodsImg(mallGoods.getPicUrl());

            if (OrderType.STORE.getValue() == orderMallBudgetVO.getOrderType().getValue()) {
                resOrderMallBudgetGoods.setGoodsPrice(mallGoods.getRetailPrice().doubleValue());
                resOrderMallBudgetGoods.setGoodsPriceStr(mallGoods.getRetailPrice().toString());
            } else {
                resOrderMallBudgetGoods.setGoodsPrice(mallGoodsNorms.getRetailPrice().doubleValue());
                resOrderMallBudgetGoods.setGoodsPriceStr(mallGoodsNorms.getRetailPrice().toString());
            }
            resOrderMallBudgetGoods.setPostagePrice(postAgePrice.doubleValue());
            MallGoodsNorms goodsNorms = mallGoodsNormsService.getById(good.getGoodsSpecId());
            resOrderMallBudgetGoods.setNorms(goodsNorms);
            goods.add(resOrderMallBudgetGoods);
        }

        //优惠券
        BigDecimal discount = new BigDecimal("0.00");
        if (orderMallBudgetVO.getVoucherId() != null) {
            MallCoupon coupon = SpringUtil.getBean(IMallCouponService.class).getById(orderMallBudgetVO.getVoucherId());
            discount = coupon.getDiscount();
        }
        if (priceTotal.compareTo(discount) < 0) {
            return HttpResult.error("优惠的金额不能大于商品总金额");
        }
        BigDecimal sum = priceTotal.add(postAgeTotal).subtract(discount);
        if (sum.doubleValue() <= 0) {
            throw new CustomException("支付金额需大于0");
        }
        resOrderMallBudget.setPricePay(sum);
        resOrderMallBudget.setPriceTotal(priceTotal);
        resOrderMallBudget.setDiscountVoucherPrice(discount);
        resOrderMallBudget.setPricePostage(postAgeTotal);
        resOrderMallBudget.setGoods(goods);
        resOrderMallBudget.setMobile(mallUser.getMobile());
        resOrderMallBudget.setRemark(orderMallBudgetVO.getRemark());
        //resOrderMallBudget.setMemberPrice(memberTotal);
        //resOrderMallBudget.setIntegral(mallUser.getCashIntegral());
        return HttpResult.ok(resOrderMallBudget);
    }

    @Override
    public ResCheckMoneyVO checkMoney(OrderMallSubmitDTO param, LoginUser loginUser) {
        BigDecimal priceTotal = new BigDecimal("0.00");
        BigDecimal pricePay = new BigDecimal("0.00");
        BigDecimal freightPrice = new BigDecimal("0.00");

        if (!Optional.ofNullable(param.getVoucherId()).isPresent()) {
            MallCoupon mallCoupon = mallCouponService.getById(param.getVoucherId());
            pricePay = pricePay.subtract(mallCoupon.getDiscount());
            priceTotal = priceTotal.subtract(mallCoupon.getDiscount());
        }

        return new ResCheckMoneyVO(priceTotal, pricePay, freightPrice);
    }


/*    @Override
    @Transactional(rollbackFor = Exception.class)
    public HttpResult<ResOrderMallSubmitVO> submitKill(OrderMallKillSubmitDTO param, LoginUser loginUser) {

        final String lockKey = param.getId() + "-RedissonLock";
        RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);
        RLock lock = redissonClient.getLock(lockKey);

        try {
            // 尝试获取锁（可重入锁,不会造成死锁）
            boolean lockFlag = lock.tryLock(30, 60, TimeUnit.SECONDS);
            if (lockFlag) {
                *//*
     * *************************************************************** 处理核心内容
     * ***************************************************************
     *//*
                RMap<Object, Object> goodsMap = redissonClient.getMap("killMap:" + param.getId(), new StringCodec());
                AtomicInteger quantity = new AtomicInteger(Integer.parseInt(goodsMap.get("inventory").toString()));
                if (quantity.get() > 0) {
                    quantity.decrementAndGet();
                    RMap<Object, Object> killUserMap = redissonClient.getMap("killUserMap:" + param.getId(),
                            new StringCodec());
                    killUserMap.put(loginUser.getAccountLogin().getUuid(), param.getId());
                    goodsMap.put("inventory", quantity);
                    System.out.println("用户：" + loginUser.getAccountLogin().getUuid() + "---抢到商品：" + param.getId());

                    // 创建阻塞队列
                    RBlockingQueue<GoodsKillVO> blockingQueue = redissonClient.getBlockingQueue("blockingQueue");
                    // 创建延迟队列
                    RDelayedQueue<GoodsKillVO> delayedQueue = redissonClient.getDelayedQueue(blockingQueue);
                    GoodsKillVO goodsKillVo = new GoodsKillVO();
                    goodsKillVo.setLoginUser(loginUser.getAccountLogin().getUuid());
                    goodsKillVo.setGoodsId(param.getId());
                    String orderSn = TenCreatUtil.getOrderNo();
                    goodsKillVo.setOrderSn(orderSn);
                    delayedQueue.offer(goodsKillVo, 60, TimeUnit.SECONDS);

                    // **************************************数据入库 start
                    MallOrderKill mallOrderKill = new MallOrderKill();
                    mallOrderKill.setKillId(param.getId());
                    mallOrderKill.setOrderSn(orderSn);
                    mallOrderKillService.save(mallOrderKill);

                    List<MallOrderGoods> goodList = new ArrayList<>();
                    BigDecimal priceTotal = BigDecimal.ZERO;
                    BigDecimal pricePay = BigDecimal.ZERO;

                    killUserMap.put("orderSn", orderSn);
                    List<MallGoods> updMallGoods = new ArrayList<>();

                    MallGoodsKill goodsKillById = mallGoodsKillService.getById(param.getId());
                    MallGoods goodEntity = mallGoodsService.getById(goodsKillById.getGoodsId());

                    goodEntity.setInventory(goodEntity.getInventory() - 1);
                    goodEntity.setCommoditySales(goodEntity.getCommoditySales() + 1);
                    MallOrderGoods item = new MallOrderGoods();
                    item.setOrderSn(orderSn);
                    item.setGoodsId(goodsKillById.getGoodsId());
                    item.setGoodsName(goodEntity.getName());
                    item.setGoodsSn(goodEntity.getGoodsSn());
                    item.setNumber(1);
                    item.setPicUrl(goodEntity.getPicUrl());
                    item.setComment(0L);
                    item.setDelFlag("0");

                    updMallGoods.add(goodEntity);
                    goodList.add(item);

                    MallAddress mallAddress = mallAddressService.getById(param.getAddressId());

                    pricePay = pricePay.add(goodsKillById.getKillPrice());
                    priceTotal = priceTotal.add(goodsKillById.getOriginPrice());

                    MallOrder mallOrder = new MallOrder();
                    mallOrder.setUuid(loginUser.getAccountLogin().getUuid());
                    mallOrder.setOrderSn(orderSn);
                    mallOrder.setOrderType(OrderType.KILL);
                    mallOrder.setStatusUser(UserOrderStatus.WAIT_PAY);
                    mallOrder.setStatusShop(ShopOrderStatus.WAIT_PAY);
                    mallOrder.setAftersaleStatus(0);
                    mallOrder.setConsignee(mallAddress.getName());
                    mallOrder.setMobile(mallAddress.getTel());
                    mallOrder.setAddress(mallAddress.getAddressDetail());
                    mallOrder.setAddressId(mallAddress.getId());
                    mallOrder.setMessage(param.getRemark());
                    mallOrder.setGoodsPrice(priceTotal);
                    mallOrder.setFreightPrice(BigDecimal.ZERO);
                    mallOrder.setCouponPrice(BigDecimal.ZERO);
                    mallOrder.setOrderPrice(priceTotal);
                    mallOrder.setActualPrice(pricePay);
                    mallOrder.setDelFlag("0");
                    save(mallOrder);
                    mallGoodsService.updateBatchById(updMallGoods);
                    mallOrderGoodsService.saveBatch(goodList);
                    // **************************************数据入库结束
                    return HttpResult.ok(new ResOrderMallSubmitVO(orderSn, pricePay));

                } else {
                    System.err.println("用户：" + loginUser.getAccountLogin().getUuid() + "---未抢到商品：" + param.getId());
                }
            } else {
                System.out.println("当前锁资源被占用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<未获取到锁");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.出现了错误");
        } finally {
            // 解锁
            lock.unlock();
        }

        return HttpResult.error();
    }*/

    @Override
    public HttpResult<MallOrderStatisticsVO> getInfoNum(MallOrder mallOrder) {
        MallOrderStatisticsVO mallOrderStatisticsVO = new MallOrderStatisticsVO();
        // 所有订单收入
        BigDecimal totalRevenue = baseMapper.queryOrderPayPrice(null, mallOrder.getUserId(), mallOrder.getBeginTime(), mallOrder.getEndTime());
        // 今日订单收人
        BigDecimal todayRevenue = baseMapper.queryOrderPayPrice(LocalDateTime.now(), mallOrder.getUserId(), mallOrder.getBeginTime(), mallOrder.getEndTime());
        // 所有订单数目
        Integer totalCount = baseMapper.queryOrderCount(null, mallOrder.getUserId(), mallOrder.getBeginTime(), mallOrder.getEndTime());
        // 今日订单数目
        Integer todayCount = baseMapper.queryOrderCount(LocalDateTime.now(), mallOrder.getUserId(), mallOrder.getBeginTime(), mallOrder.getEndTime());


        mallOrderStatisticsVO.setTotalOrderRevenue(totalRevenue);
        mallOrderStatisticsVO.setTodayRevenue(todayRevenue);
        mallOrderStatisticsVO.setOrderNum(totalCount);
        mallOrderStatisticsVO.setTodayOrderNum(todayCount);
        mallOrderStatisticsVO.setOrderRevenue(totalRevenue);
        mallOrderStatisticsVO.setTodayOrderRevenue(todayRevenue);

        return HttpResult.ok(mallOrderStatisticsVO);
    }

    @Override
    public HttpResult<String> selectOrderNum(MallOrder mallOrder) throws ParseException {
        Map<String, Object> param = mallOrder.getParams();
        param.put("StatusUser", UserOrderStatus.OK.getValue());
        mallOrder.setParams(param);
        List<DateAndDataVO> dateAndDataVOS = baseMapper.countNewOrderNum(mallOrder);
        // 将所有日期转成时间戳
        List<Object[]> result = new ArrayList<>(dateAndDataVOS.size());
        for (DateAndDataVO item : dateAndDataVOS) {

            result.add(new Object[]{DateUtils.dateTime("yyyy-MM-dd", DateUtils.dateTime(item.getDbDate())).getTime(),
                    item.getDbData()});
        }
        return HttpResult.ok(JSONObject.toJSONString(result));
    }

    @Override
    public HttpResult<MallOrderVO> selectOrderDetailsById(ReqIdParam reqIdParam) {
        MallOrder mallOrder = lambdaQuery().eq(MallOrder::getId, reqIdParam.getId()).one();
        MallUser mallUserServiceOne = mallUserService
                .getOne(new QueryWrapper<MallUser>().eq("uuid", mallOrder.getUuid()));
        MallOrderVO mallOrderVO = new MallOrderVO();
        BeanUtils.copyProperties(mallOrderVO, mallOrder);
        BeanUtils.copyProperties(mallOrderVO, mallUserServiceOne);
        List<MallOrderGoods> orderGoods = mallOrderGoodsService
                .list(new QueryWrapper<MallOrderGoods>().eq("order_sn", mallOrder.getOrderSn()));
        mallOrderVO.setGoods(orderGoods);
        mallOrderVO.setNumber(orderGoods.size());
        return HttpResult.ok(mallOrderVO);
    }

    @Override
    @Transactional
    public HttpResult<Boolean> ship(MallOrderShipDTO mallOrderShipPO) {
        MallOrder mallOrder = lambdaQuery().eq(MallOrder::getId, mallOrderShipPO.getId()).one();
        mallOrder.setOrderStatus(OrderStatus.WAIT_RECEIVED);
        mallOrder.setStatusShop(ShopOrderStatus.WAIT_RECEIVED);
        mallOrder.setStatusUser(UserOrderStatus.WAIT_RECEIVED);
        mallOrder.setShipSn(mallOrderShipPO.getShipSn());
        mallOrder.setShipChannel(mallOrderShipPO.getShipChannel());
        mallOrder.setShipTime(new Date());
        mallOrder.setMobile(mallOrderShipPO.getMobile());
        mallOrder.setAddress(mallOrderShipPO.getAddress());
        mallOrder.setConsignee(mallOrderShipPO.getConsignee());

        MallOrderGoods mallOrderGoods = mallOrderGoodsService
                .getOne(new QueryWrapper<MallOrderGoods>().eq("id", mallOrderShipPO.getOrderGoodsId()));
        mallOrderGoods.setOrderStatus(OrderStatus.WAIT_RECEIVED);
        mallOrderGoods.setShipSn(mallOrderShipPO.getShipSn());
        mallOrderGoods.setShipChannel(mallOrderShipPO.getShipChannel());
        mallOrderGoods.setShipTime(new Date());
        mallOrderGoods.setMobile(mallOrderShipPO.getMobile());
        mallOrderGoods.setAddress(mallOrderShipPO.getAddress());
        mallOrderGoods.setConsignee(mallOrderShipPO.getConsignee());

        mallOrderGoodsService.updateById(mallOrderGoods);

        mallMessageInformService.addOrderMessage("您的商品已发货", mallOrderGoods.getId(), mallOrder.getUuid());
        return HttpResult.ok(updateMallOrder(mallOrder) > 0);
    }

    @Override
    public HttpResult<MallOrderStatisticsVO> getInfo(MallOrder mallOrder) {

        //获取当前月份
        LocalDate currentDate = LocalDate.now();
        //获取月份第一天
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        //获取月份的最后一天
        LocalDate lastDayOfMonth = currentDate.withDayOfMonth(currentDate.lengthOfMonth());

        LocalDateTime localDateTimeFirst = firstDayOfMonth.atStartOfDay();
        LocalDateTime localDateTimeLast = lastDayOfMonth.atStartOfDay();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
//        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateStr = localDateTimeFirst.format(dateTimeFormatter);


        List<MallUser> list = mallUserService.list();
        Integer todayUserCount = mallUserService.lambdaQuery().apply("date_format(create_time,'%Y%m%d') = " + "'" + LocalDateTime.now() + "'").count();
        // 所有订单收入
        BigDecimal totalRevenue = baseMapper.queryOrderPayPrice(null, mallOrder.getUserId(), null, null);
        // 今日订单收人
        BigDecimal todayRevenue = baseMapper.queryOrderPayPrice(LocalDateTime.now(), mallOrder.getUserId(), null, null);
        // 所有订单数目
        Integer totalCount = baseMapper.queryOrderCount(null, mallOrder.getUserId(), null, null);
        // 今日订单数目
        Integer todayCount = baseMapper.queryOrderCount(LocalDateTime.now(), mallOrder.getUserId(), null, null);
        //本月订单收入
        BigDecimal monthOrderRevenue = baseMapper.queryOrderPayPrice(null, mallOrder.getUserId(), dateStr, localDateTimeLast);

        Integer count = 0;
        Integer todayGoodsCount = 0;
        Integer count1 = 0;
        Integer todayGoodsCount1 = 0;
        BigDecimal totalOut = BigDecimal.ZERO;
        BigDecimal todayOut = BigDecimal.ZERO;

        SysUser sysUser = sysUserService.selectUserById(mallOrder.getUserId());
        if (mallOrder.getUserId() != null && sysUser.getStore() == 2) {
            // 所有上架商品数量
            count = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getSupplier, 1)
                    .eq(MallGoods::getIsOnSale, 1)
                    .eq(MallGoods::getAuditStatus, 1)
                    .count();
            // 今日上架
//            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            todayGoodsCount = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getSupplier, 1)
                    .eq(MallGoods::getIsOnSale, 1)
                    .eq(MallGoods::getAuditStatus, 1)
                    .apply("date_format(create_time,'%Y%m%d') = " + "'" + dateTimeFormatter.format(LocalDateTime.now()) + "'")
                    .count();
            // 待通过数量
            count1 = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getSupplier, 1)
                    .eq(MallGoods::getAuditStatus, 0)
                    .count();
            todayGoodsCount1 = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getSupplier, 1)
                    .eq(MallGoods::getAuditStatus, 0)
                    .apply("date_format(create_time,'%Y%m%d') = " + "'" + dateTimeFormatter.format(LocalDateTime.now()) + "'")
                    .count();
            // 所有订单支出
            totalOut = baseMapper.queryOrderOut(null, mallOrder.getUserId());
            // 今日订单支出
            todayOut = baseMapper.queryOrderOut(LocalDateTime.now(), mallOrder.getUserId());
        }
        if (mallOrder.getUserId() != null && sysUser.getStore() == 1) {
            // 所有上架商品数量
            count = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getStore, 1)
                    .eq(MallGoods::getIsOnSale, 1)
                    .eq(MallGoods::getAuditStatus, 1)
                    .count();
            // 今日上架
//            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            todayGoodsCount = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getStore, 1)
                    .eq(MallGoods::getIsOnSale, 1)
                    .eq(MallGoods::getAuditStatus, 1)
                    .apply("date_format(create_time,'%Y%m%d') = " + "'" + dateTimeFormatter.format(LocalDateTime.now()) + "'")
                    .count();
            // 待通过数量
            count1 = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getStore, 1)
                    .eq(MallGoods::getAuditStatus, 0)
                    .count();
            todayGoodsCount1 = mallGoodsService.lambdaQuery().eq(MallGoods::getUserId, mallOrder.getUserId())
                    .eq(MallGoods::getStore, 1)
                    .eq(MallGoods::getAuditStatus, 0)
                    .apply("date_format(create_time,'%Y%m%d') = " + "'" + dateTimeFormatter.format(LocalDateTime.now()) + "'")
                    .count();
            // 所有订单支出
            totalOut = baseMapper.queryOrderOut(null, mallOrder.getUserId());
            // 今日订单支出
            todayOut = baseMapper.queryOrderOut(LocalDateTime.now(), mallOrder.getUserId());
        }


        MallOrderStatisticsVO mallOrderStatisticsVO = new MallOrderStatisticsVO();
        mallOrderStatisticsVO.setOrderNum(totalCount != null ? totalCount : 0);
        mallOrderStatisticsVO.setTodayOrderNum(todayCount != null ? todayCount : 0);
        mallOrderStatisticsVO.setOrderRevenue(totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        mallOrderStatisticsVO.setTodayRevenue(todayRevenue != null ? todayRevenue : BigDecimal.ZERO);
        mallOrderStatisticsVO.setUserNum(list.size());
        mallOrderStatisticsVO.setTodayUserNum(todayUserCount);
        mallOrderStatisticsVO.setGoodsNum(count);
        mallOrderStatisticsVO.setTodayGoodsNum(todayGoodsCount);
        mallOrderStatisticsVO.setWaitGoodsNum(count1);
        mallOrderStatisticsVO.setWaitTodayGoodsNum(todayGoodsCount1);
        mallOrderStatisticsVO.setOrderOut(totalOut);
        mallOrderStatisticsVO.setTodayOut(todayOut);
        mallOrderStatisticsVO.setMonthOrderRevenue(monthOrderRevenue != null ? monthOrderRevenue : BigDecimal.ZERO);
        return HttpResult.ok(mallOrderStatisticsVO);
    }

    @Override
    public HttpResult<Boolean> confirmOrder(ReqIdParam idParam, LoginUser loginUser) {
        MallOrderGoods orderGoods = mallOrderGoodsService.lambdaQuery().eq(MallOrderGoods::getOrderSn, idParam.getId()).eq(MallOrderGoods::getNormsId, idParam.getNormsId()).one();

        orderGoods.setOrderStatus(OrderStatus.DAI_CENTXT);
        orderGoods.setConfirmTime(LocalDateTime.now());
        if (orderGoods.getOrderType().equals(OrderType.SHOP)) {
            mallMessageInformService.addOrderMessage("您的商品已收货成功", orderGoods.getId(), loginUser.getAccountLogin().getUuid());
        }
        if (orderGoods.getOrderType().equals(OrderType.STORE)) {
            mallMessageInformService.addOrderMessage("您的商品已核销成功", orderGoods.getId(), loginUser.getAccountLogin().getUuid());
        }
        handleData(orderGoods);


        return HttpResult.ok(mallOrderGoodsService.updateById(orderGoods));
    }

    /**
     * 处理货款及收益
     *
     * @param orderGoods
     */
    @Override
    public void handleData(MallOrderGoods orderGoods) {

        //算出该用户消费总金额
        MallAdminOrderStatisticsVO mallAdminOrderStatisticsVO = baseMapper.orderConsume(orderGoods.getUuid());
        if (mallAdminOrderStatisticsVO.getOverMoney() != null) {
            //查到字典数据:
            List<SysDictData> wxPayConfig = DictUtils.getDictCache("recharge_limit");
            if (wxPayConfig != null) {
                wxPayConfig.forEach(x -> {
                    BigDecimal amount = orderGoods.getPayPrice();
                    BigDecimal actualPush = amount.multiply(new BigDecimal(x.getDictValue()).divide(BigDecimal.valueOf(100), 6, BigDecimal.ROUND_DOWN)).setScale(2, BigDecimal.ROUND_DOWN);
                    //消费小于20W则是smallConsume增加代采购额度
                    if (mallAdminOrderStatisticsVO.getOverMoney().compareTo(new BigDecimal(200000)) < 0) {
                        if ("smallConsume".equals(x.getDictLabel())) {
                            rabbitUtils.sendBalanceMessage(orderGoods.getUuid(), actualPush, AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.RECHARGE_CONSUME, "消费小于20W增加代采购额度", orderGoods.getOrderGoodsSn(), BalanceTypeEnum.RECHARGE_LIMIT_CHANGE);
                        }
                    }
                    //消费超过20W则是按照bigConsume增加代采购额度
                    else {
                        if ("bigConsume".equals(x.getDictLabel())) {
                            rabbitUtils.sendBalanceMessage(orderGoods.getUuid(), actualPush, AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.RECHARGE_CONSUME, "消费不小于20W增加代采购额度", orderGoods.getOrderGoodsSn(), BalanceTypeEnum.RECHARGE_LIMIT_CHANGE);
                        }
                    }
                });
            }
        }


        //供应商商品应将货款打入账户
        MallGoods mallGoods = mallGoodsService.getById(orderGoods.getGoodsId());
        if (mallGoods.getSupplier() == 1) {
            BalanceChange balanceChange = balanceChangeService.lambdaQuery()
                    .eq(BalanceChange::getSource, orderGoods.getOrderGoodsSn())
                    .eq(BalanceChange::getBusinessType, BalanceBusinessType.ORDER_ADD)
                    .eq(BalanceChange::getBalanceType, BalanceTypeEnum.FINANCE_WAIT)
                    .one();
            if (balanceChange != null) {
                // 减少待结算货款
                rabbitUtils.sendBalanceMessage(balanceChange.getUuid(), balanceChange.getChangAmount().negate(), AllEnum.BalanceChangeTypeEnums.EXPENDITURE.getType(), BalanceBusinessType.ORDER_CONFIRM, "确认收货", balanceChange.getSource(), BalanceTypeEnum.FINANCE_WAIT);
                // 增加货款
                rabbitUtils.sendBalanceMessage(balanceChange.getUuid(), balanceChange.getChangAmount().abs(), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.ORDER_CONFIRM, "确认收货", balanceChange.getSource(), BalanceTypeEnum.FINANCE);

            }
            // 增加累积收益减少待结算收益
            List<BalanceChange> list = balanceChangeService.lambdaQuery()
                    .eq(BalanceChange::getSource, orderGoods.getOrderGoodsSn())
                    .in(BalanceChange::getBusinessType, BalanceBusinessType.DIRECT_REFERRER, BalanceBusinessType.INDIRECT_REFERRER)
                    .eq(BalanceChange::getBalanceType, BalanceTypeEnum.WAIT_INCOME)
                    .list();
            for (BalanceChange balanceChange1 : list) {
                // 减少待结算收益
                rabbitUtils.sendBalanceMessage(balanceChange1.getUuid(), balanceChange1.getChangAmount().negate(), AllEnum.BalanceChangeTypeEnums.EXPENDITURE.getType(), BalanceBusinessType.ORDER_CONFIRM, "确认收货", balanceChange1.getSource(), BalanceTypeEnum.WAIT_INCOME);
                // 增加收益
                rabbitUtils.sendBalanceMessage(balanceChange1.getUuid(), balanceChange1.getChangAmount().abs(), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), balanceChange1.getBusinessType(), "确认收货", balanceChange1.getSource(), BalanceTypeEnum.INCOME);
                // 增加余额
                rabbitUtils.sendBalanceMessage(balanceChange1.getUuid(), balanceChange1.getChangAmount().abs(), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), balanceChange1.getBusinessType(), "确认收货", balanceChange1.getSource(), BalanceTypeEnum.BALANCE);
            }
        }
        if (mallGoods.getStore() == 1) {
            BalanceChange balanceChange = balanceChangeService.lambdaQuery()
                    .eq(BalanceChange::getSource, orderGoods.getOrderGoodsSn())
                    .eq(BalanceChange::getBusinessType, BalanceBusinessType.STORE_SALE)
                    .eq(BalanceChange::getBalanceType, BalanceTypeEnum.STORE_FINANCE_WAIT)
                    .one();

            if (balanceChange != null) {
                // 减少待结算货款
                rabbitUtils.sendBalanceMessage(balanceChange.getUuid(), balanceChange.getChangAmount().negate(), AllEnum.BalanceChangeTypeEnums.EXPENDITURE.getType(), BalanceBusinessType.VERIFICATION, "核销", balanceChange.getSource(), BalanceTypeEnum.STORE_FINANCE_WAIT);
                // 增加货款
                rabbitUtils.sendBalanceMessage(balanceChange.getUuid(), balanceChange.getChangAmount().abs(), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.VERIFICATION, "核销", balanceChange.getSource(), BalanceTypeEnum.STORE_FINANCE);

            }

            // 增加累积收益减少待结算收益
            List<BalanceChange> list = balanceChangeService.lambdaQuery()
                    .eq(BalanceChange::getSource, orderGoods.getOrderGoodsSn())
                    .in(BalanceChange::getBusinessType, BalanceBusinessType.DIRECT_REFERRER, BalanceBusinessType.INDIRECT_REFERRER)
                    .eq(BalanceChange::getBalanceType, BalanceTypeEnum.WAIT_INCOME)
                    .list();
            for (BalanceChange balanceChange1 : list) {
                // 减少待结算收益
                rabbitUtils.sendBalanceMessage(balanceChange1.getUuid(), balanceChange1.getChangAmount().negate(), AllEnum.BalanceChangeTypeEnums.EXPENDITURE.getType(), BalanceBusinessType.VERIFICATION, "核销", balanceChange1.getSource(), BalanceTypeEnum.WAIT_INCOME);
                // 增加收益
                rabbitUtils.sendBalanceMessage(balanceChange1.getUuid(), balanceChange1.getChangAmount().abs(), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), balanceChange1.getBusinessType(), "核销", balanceChange1.getSource(), BalanceTypeEnum.INCOME);
                // 增加余额
                rabbitUtils.sendBalanceMessage(balanceChange1.getUuid(), balanceChange1.getChangAmount().abs(), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), balanceChange1.getBusinessType(), "核销", balanceChange1.getSource(), BalanceTypeEnum.BALANCE);
            }

        }

        // 商品参与分佣 增加待结算收益
        if (mallGoods.getIsBonus() == 1) {
            income(orderGoods, mallGoods);
        }
    }

    private void income(MallOrderGoods order, MallGoods goods) {
        //找到商品所对应的商家
        SysUser sysUser = sysUserService.selectUserById(goods.getUserId());
        //商家用户
        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getMobile, sysUser.getPhonenumber()).one();
        if (one != null) {
            if (Stream.of(OrderType.STORE, OrderType.SHOP).anyMatch(orderType -> orderType.compareTo(order.getOrderType()) == 0)) {
                List<SysDictData> wxPayConfig = DictUtils.getDictCache("dividend");
                if (wxPayConfig != null) {
                    MallUser parent = mallUserService.lambdaQuery().eq(MallUser::getUuid, one.getReferrerUuid()).one();
                    if (parent != null) {
                        wxPayConfig.forEach(x -> {
                            BigDecimal amount = order.getPayPrice();
                            BigDecimal actualPush = amount.multiply(new BigDecimal(x.getDictValue()).divide(BigDecimal.valueOf(100), 6, BigDecimal.ROUND_DOWN)).setScale(2, BigDecimal.ROUND_DOWN);
                            if ("storeReferrer".equals(x.getDictLabel())) {
                                rabbitUtils.sendBalanceMessage(parent.getUuid(), actualPush, AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.STORE_REFERRER, "推荐商家奖励-直推", order.getOrderGoodsSn(), BalanceTypeEnum.CONSUMER_ROLL);
                            }
                            if ("inStoreReferrer".equals(x.getDictLabel())) {
                                rabbitUtils.sendBalanceMessage(parent.getReferrerUuid(), actualPush, AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.IN_STORE_REFERRER, "推荐商家奖励-间推", order.getOrderGoodsSn(), BalanceTypeEnum.CONSUMER_ROLL);
                            }
                        });
                    }
                }
            }
        }


    }

    @Override
    public HttpResult<List<MallNewOrderVO>> selectNewOrders(MallOrder mallOrder) {
        List<MallOrder> mallOrders = baseMapper.selectOrderList(mallOrder);
        List<MallNewOrderVO> mallNewOrders = new ArrayList<>();
        for (MallOrder order : mallOrders) {
            MallNewOrderVO mallNewOrder = new MallNewOrderVO();
            MallUser mallUserServiceOne = mallUserService.getOne(new QueryWrapper<MallUser>().eq("uuid", order.getUuid()));
            mallNewOrder.setUsername(mallUserServiceOne == null ? "" : mallUserServiceOne.getUsername());
            mallNewOrder.setActualPrice(order.getActualPrice());
            mallNewOrder.setUuId(order.getUuid());
            mallNewOrder.setOrderSn(order.getOrderSn());
            mallNewOrder.setOrderType(order.getOrderType());
            mallNewOrder.setCreateTime(order.getCreateTime());
            mallNewOrders.add(mallNewOrder);
        }
        mallNewOrders.stream().sorted(Comparator.comparing(MallNewOrderVO::getCreateTime).reversed())
                .collect(Collectors.toList());

        return HttpResult.ok(mallNewOrders);
    }


    @Override
    public Page<MallOrder> page(IPage<MallOrder> page, MallOrder mallOrder) {
        if (mallOrder.getOrderType() != null) {
            mallOrder.setOrderTypeValue(mallOrder.getOrderType().getValue());
        }
        Page<MallOrder> page1 = baseMapper.page(page, mallOrder);
        page1.getRecords().forEach(item -> {
            item.setOrderTypeDesc(item.getOrderType() != null ? item.getOrderType().getDesc() : "-");
            item.setSupplyPrice(item.getSupplyPrice() == null ? item.getActualPrice().divide(new BigDecimal(2), 2, BigDecimal.ROUND_DOWN) : item.getSupplyPrice());

            if (item.getAftersaleStatus() == AfterSaleStatus.BUYER_DEAL.getValue()
                    || item.getAftersaleStatus() == AfterSaleStatus.DEL_PAY.getValue()
                    || item.getAftersaleStatus() == AfterSaleStatus.WAIT_RECEIVED.getValue()
                    || item.getAftersaleStatus() == AfterSaleStatus.ALREADY_APPLIED.getValue()) {
                item.setOrderStatusDesc("已售后");
            } else {
                item.setOrderStatusDesc(item.getOrderStatus() != null ? item.getOrderStatus().getDesc() : "-");
            }
            item.setAftersaleStatusDesc(AfterSaleStatus.getName(item.getAftersaleStatus()));
            if (null != item.getPayType()) {
                item.setPayTypeDesc(item.getPayType().getDesc());
            } else {
                item.setPayTypeDesc("-");
            }
            if (item.getUserId() != null) {
                if (item.getUserId() == 1L) {
                    item.setUsername("平台");
                }
                if (item.getUserId() == 2L) {
                    item.setUsername("开发");
                }
            }

        });
        return page1;
    }

    @Override
    public ResOrderDetailInfoVO getOrderDetail(ReqIdParam id) {
        Long orderId = id.getId();

        ResOrderDetailInfoVO detail = new ResOrderDetailInfoVO();

        MallOrder mallOrder = lambdaQuery().eq(MallOrder::getId, orderId).one();

        LambdaQueryChainWrapper<MallOrderGoods> wrapper = mallOrderGoodsService.lambdaQuery();
        wrapper.eq(MallOrderGoods::getOrderSn, mallOrder.getOrderSn());
        if (id.getGoodId() != null) {
            wrapper.eq(MallOrderGoods::getId, id.getGoodId());
        }
        List<MallOrderGoods> orderGoodList = wrapper.list();
        List<ResOrderDetailInfoVO.GoodsInfo> goodsInfos = new ArrayList<>();
        if (orderGoodList.isEmpty()) {
            throw new CustomException("没有找到订单下的商品");
        }
        MallOrderGoods good = mallOrderGoodsService.lambdaQuery().eq(MallOrderGoods::getOrderGoodsSn, orderGoodList.get(0).getOrderGoodsSn() != null ? orderGoodList.get(0).getOrderGoodsSn() : mallOrder.getOrderSn()).one();
        if (good == null) {
            throw new CustomException("没有找到订单下的商品");
        }

        MallGoods one = mallGoodsService.lambdaQuery().eq(MallGoods::getId, good.getGoodsId()).one();
        if (one == null) {
            throw new CustomException("订单下的商品找不到了");
        }

        detail.setOrderDetail(ResOrderDetailInfoVO.OrderDetail.builder()
                .orderSn(orderGoodList.get(0).getOrderGoodsSn() != null ? orderGoodList.get(0).getOrderGoodsSn() : mallOrder.getOrderSn())
                .generateTime(mallOrder.getCreateTime())
                .orderStatus(orderGoodList.get(0).getOrderStatus())
                .payAmount(orderGoodList.get(0).getPayPrice())
                .payType(mallOrder.getPayType() == null ? "" : mallOrder.getPayType().getDesc())
                .afterSaleStatus(orderGoodList.get(0).getAftersaleStatus())
                .remark(mallOrder.getMessage())
                .createTime(mallOrder.getCreateTime())
                .payTime(mallOrder.getPayTime())
                .endTime(mallOrder.getEndTime())
                .updateTime(orderGoodList.get(0).getUpdateTime())
                .supplyPrice(one.getSupplyPrice() != null ? one.getSupplyPrice() : (new BigDecimal(0.0)))
                .build());
        for (MallOrderGoods orderGoods : orderGoodList) {
            MallGoods goods = mallGoodsService.lambdaQuery().eq(MallGoods::getId, orderGoods.getGoodsId()).one();
            if (goods == null) {
                throw new CustomException("订单下的商品找不到了");
            }
            String supplierPhone = "";
            String supplierName = "";
            String storeName = "";
            String storePhone = "";
            String chainName = "";
            String chainPhone = "";
            Integer store = MallConstants.MALL_FALSE;
            Integer chain = MallConstants.MALL_FALSE;
            Integer supplier = MallConstants.MALL_FALSE;
            if (Long.valueOf(MallConstants.MALL_TRUE).equals(goods.getSupplier())) {
                SysUser sysUser = SpringUtil.getBean(ISysUserService.class).selectUserById(goods.getUserId());
                supplierName = sysUser == null ? "" : sysUser.getUserName();
                supplierPhone = sysUser == null ? "" : sysUser.getPhonenumber();
                supplier = MallConstants.MALL_TRUE;
            }
            if (goods.getStore().equals(Long.valueOf(MallConstants.MALL_TRUE))) {
//                SysUser sysUser = SpringUtil.getBean(ISysUserService.class).selectUserById(goods.getUserId());
                MallStore mallStore = mallStoreService.selectUserById(goods.getUserId());
                storeName = mallStore == null ? "" : mallStore.getStoreName();
                storePhone = mallStore == null ? "" : mallStore.getMobile();
                store = MallConstants.MALL_TRUE;
            }
            if (MallConstants.MALL_TRUE.equals(goods.getChain())) {
                SysUser sysUser = SpringUtil.getBean(ISysUserService.class).selectUserById(goods.getUserId());

                chainName = "合囤供应链";
                chainPhone = sysUser == null ? "" : sysUser.getPhonenumber();
                chain = MallConstants.MALL_TRUE;
            }
            MallCategory mallCategory = SpringUtil.getBean(IMallCategoryService.class).lambdaQuery().eq(MallCategory::getId, goods.getCategoryId()).one();
            MallCategory top = mallCategoryService.lambdaQuery().eq(MallCategory::getId, mallCategory.getPid()).one();
            MallGoodsNorms mallGoodsNorms = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getId, orderGoods.getNormsId()).select(MallGoodsNorms::getGoodsId, MallGoodsNorms::getAttribute, MallGoodsNorms::getSupplyPrice).one();
            ResOrderDetailInfoVO.GoodsInfo goodsInfo = ResOrderDetailInfoVO.GoodsInfo.builder()
                    .id(goods.getUserId())
                    .goodsId(orderGoods.getGoodsId())
                    .goodsName(orderGoods.getGoodsName())
                    .picUrl(orderGoods.getPicUrl())
                    .category(mallCategory == null ? "" : mallCategory.getName())
                    .topCategory(top == null ? "" : top.getName())
                    .orderType(mallOrder.getOrderType())
                    .goodsNum(orderGoods.getNumber())
                    .supplierPhone(supplierPhone)
                    .supplierName(supplierName)
                    .storePhone(storePhone)
                    .storeName(storeName)
                    .chainName(chainName)
                    .actualPrice(orderGoods.getPayPrice())
                    .price(orderGoods.getPrice())
                    .couponPrice(orderGoods.getCouponPrice())
                    .attribute(mallGoodsNorms.getAttribute())
                    .supplyPrice(goods.getStore().equals(Long.valueOf(MallConstants.MALL_TRUE)) ? goods.getSupplyPrice() : mallGoodsNorms.getSupplyPrice().multiply(new BigDecimal(orderGoods.getNumber())))
                    .shipTime(orderGoods.getShipTime())
                    .confirmTime(orderGoods.getConfirmTime())
                    .store(store)
                    .supplier(supplier)
                    .chain(chain)
                    .build();
            goodsInfos.add(goodsInfo);

        }
        detail.setGoodsInfo(goodsInfos);
        MallUser user = mallUserService.lambdaQuery().eq(MallUser::getUuid, mallOrder.getUuid()).one();

        detail.setUserInfo(ResOrderDetailInfoVO.UserInfo.builder()
                .uuid(mallOrder.getUuid())
                .orderGoodsSn(detail.getOrderDetail().getOrderSn())
                .remarks(mallOrder.getMessage())
                .userPhone(user == null ? "" : user.getMobile())
                .address(orderGoodList.get(0).getAddress() != null ? orderGoodList.get(0).getAddress() : mallOrder.getAddress())
                .consignee(orderGoodList.get(0).getConsignee() != null ? orderGoodList.get(0).getConsignee() : mallOrder.getConsignee())
                .consigneePhone(orderGoodList.get(0).getMobile() != null ? orderGoodList.get(0).getMobile() : mallOrder.getMobile())
                .nickName(user == null ? "" : user.getNickname())
                .build());

        MallAftersale aftersale = SpringUtil.getBean(IMallAftersaleService.class).lambdaQuery().eq(MallAftersale::getOrderId, orderId).eq(MallAftersale::getOrderGoodsId, id.getGoodId()).one();
        detail.setAftersaleInfo(ResOrderDetailInfoVO.AfterSaleInfo.builder()
                .uuid(mallOrder.getUuid())
                .userPhone(user == null ? "" : user.getMobile())
                .describe(aftersale == null ? "" : aftersale.getReason())
                .refundAmount(aftersale == null ? new BigDecimal(0) : aftersale.getAmount())
                .images(aftersale == null || aftersale.getPictures() == null ? null : Arrays.asList(aftersale.getPictures().split(",")))
                .createTime(aftersale == null ? null : aftersale.getCreateTime())
                .endTime(aftersale == null ? null : aftersale.getEndTime())
                .type(aftersale == null ? null : aftersale.getType())
                .build());

        //快递
        if (StrUtil.isNotEmpty(orderGoodList.get(0).getShipSn())) {
            HttpResult<?> httpResult = LogisticsUtils.checkLogistics(orderGoodList.get(0).getShipSn());
            detail.setLogisticsInfo((JSONObject) httpResult.getData());
        } else {
            detail.setLogisticsInfo(null);
        }
        // 退货物流

        if (null != aftersale && StrUtil.isNotEmpty(aftersale.getShipSn())) {
            HttpResult<?> httpResult = LogisticsUtils.checkLogistics(aftersale.getShipSn());
            detail.setLogisticsInfo2((JSONObject) httpResult.getData());
        } else {
            detail.setLogisticsInfo2(null);
        }
        return detail;
    }

    @Override
    public HttpResult<List<Map<String, Object>>> getOrderNumDaily(MallUserAndOrderTimeDTO dto) {
        List<Map<String, Object>> res = new ArrayList<>();
        if (dto.getBeginTime() == null || dto.getEndTime() == null) {
            LocalDateTime endOfDay = LocalDateTimeUtil.endOfDay(LocalDateTime.now());
            MallUser mallUser = mallUserService.lambdaQuery().orderByAsc(BaseEntity::getCreateTime).last("limit 1").one();
            String startTime = DateUtil.format(mallUser.getCreateTime(), "yyyy-MM-dd");
            String endTime = DateUtil.format(endOfDay, "yyyy-MM-dd");
            dto.setBeginTime(startTime);
            dto.setEndTime(endTime);
        }
        try {
            List<String> betweenDays = DateUtils.getBetweenDays(dto.getBeginTime(), dto.getEndTime());

            if (betweenDays == null) {
                return HttpResult.error();
            }
            Map<String, Object> userMap = null;
            if (dto.getType() == 1) {
                List<StatisticsDateVO> userNumDailyV2 = baseMapper.getUserNumDailyV2();
                userMap = userNumDailyV2.stream().collect(Collectors.toMap(StatisticsDateVO::getDate, StatisticsDateVO::getNum, (key1, key2) -> key2));
            }
            if (dto.getType() == 2) {
                List<StatisticsDateVO> orderIncomeDailyV2 = baseMapper.getOrderIncomeDailyV2(dto.getUserId());
                userMap = orderIncomeDailyV2.stream().collect(Collectors.toMap(StatisticsDateVO::getDate, StatisticsDateVO::getNum, (key1, key2) -> key2));
            }
            if (dto.getType() == 3) {
                List<StatisticsDateVO> orderNumDailyV2 = baseMapper.getOrderNumDailyV2(dto.getUserId());
                userMap = orderNumDailyV2.stream().collect(Collectors.toMap(StatisticsDateVO::getDate, StatisticsDateVO::getNum, (key1, key2) -> key2));
            }
            for (String day : betweenDays) {
                Map<String, Object> data = new HashMap<>();
                data.put("date", day);
                if (userMap == null) {
                    data.put("num", 0);
                    continue;
                }
                // 新增用户折线图
                if (userMap.get(day) != null) {
                    data.put("num", userMap.get(day));
                } else {
                    data.put("num", 0);
                }
                res.add(data);
            }
            return HttpResult.ok(res);
        } catch (ParseException e) {
            return HttpResult.error("日期解析失败");
        }
    }

    @Override
    public HttpResult<List<Map<String, Object>>> getUserNumDaily(MallUser params) {
        List<Map<String, Object>> res = new ArrayList<>();
        Map<String, Object> map = params.getParams();
        try {
            List<String> betweenDays = DateUtils.getBetweenDays(String.valueOf(map.get("beginTime")), String.valueOf(map.get("endTime")));

            if (betweenDays == null) {
                return HttpResult.error();
            }
            for (String day : betweenDays) {
                Map<String, Object> data = new HashMap<>();
                data.put("date", day);
                data.put("num", baseMapper.getUserNumDaily(day));
                res.add(data);
            }
            return HttpResult.ok(res);
        } catch (ParseException e) {
            return HttpResult.error("日期解析失败");
        }
    }

    @Override
    public HttpResult<Boolean> delAppOrder(ReqIdParam param) {
        MallOrder byId = getById(param.getOrderId());
        if (byId == null) {
            return HttpResult.error("无该订单");
        }
        baseMapper.deleteById(param.getOrderId());
        byId.setAppDel(true);
        updateById(byId);
        return HttpResult.ok();
    }

    /*******
     * 取消订单
     * @param param
     * @return
     */
    @Override
    public HttpResult<Boolean> cancelPayOrder(ReqIdParam param) {
        MallOrder mallOrder = getById(param.getId());
        if (mallOrder == null) {
            return HttpResult.error("无该订单");
        }
        List<MallGoodsNorms> goodsNorms = new ArrayList();
        List<MallGoods> goods = new ArrayList();
        List<MallOrderGoods> list = mallOrderGoodsService.lambdaQuery().eq(MallOrderGoods::getOrderSn, mallOrder.getOrderSn()).list();
        for (MallOrderGoods orderGoods : list) {
            //更改订单状态
            orderGoods.setOrderStatus(OrderStatus.DEL_PAY);
            mallOrderGoodsService.updateMallOrderGoods(orderGoods);

            //增加售商品库存（规格）
            MallGoodsNorms mallGoodsNorms = mallGoodsNormsService.lambdaQuery().eq(MallGoodsNorms::getId, orderGoods.getNormsId()).one();
            if (mallGoodsNorms != null) {
                mallGoodsNorms.setInventory(mallGoodsNorms.getInventory() + orderGoods.getNumber());
                goodsNorms.add(mallGoodsNorms);
            }
            // 增加商品库存
            MallGoods one = mallGoodsService.lambdaQuery().eq(MallGoods::getId, orderGoods.getGoodsId()).one();
            one.setInventory(one.getInventory() + orderGoods.getNumber());
            one.setCommoditySales(one.getCommoditySales() - 1);
        }
        mallOrder.setStatusUser(UserOrderStatus.CANCEL_PAY);
        mallOrder.setOrderStatus(OrderStatus.DEL_PAY);
        updateById(mallOrder);
        mallGoodsService.updateBatchById(goods);
        mallGoodsNormsService.updateBatchById(goodsNorms);

        //优惠券返回
        if (mallOrder.getCouponId() != null) {
            mallCouponUserService.updateState(mallOrder.getId(), mallOrder.getUuid(), AllEnum.couponType.EXISTENCE.getType());
        }
        return HttpResult.ok();
    }

    /****
     * 申请售后
     * @param param
     * @return
     */
    @Override
    public HttpResult<Boolean> afterSaleOrder(ReqIdParam param) {
        MallOrderGoods orderGoods = mallOrderGoodsService.getById(param.getId());
        if (orderGoods == null) {
            return HttpResult.error("无该订单");
        }
        orderGoods.setAftersaleStatus(AfterSaleStatus.ALREADY_APPLIED.getValue());
        mallOrderGoodsService.updateById(orderGoods);
        return HttpResult.ok();
    }

    /*****
     * 10分钟未支付 取消订单 后者拼团砍价没成功取消订单
     * @param orderVO
     * @return
     */
    @Lock4j(name = Lock4jConstant.CANCEL_ORDER, keys = "#orderVO.orderSn", acquireTimeout = 30000)
    @Override
    public HttpResult<Boolean> cancelOrder(OrderVO orderVO) {
        //未支付取消订单
        MallOrder mallOrder = lambdaQuery().eq(MallOrder::getOrderSn, orderVO.getOrderSn()).one();
        if (mallOrder == null) {
            log.info("没有订单信息为{}", orderVO);
            return HttpResult.ok(true);
        }
        if (mallOrder.getOrderStatus().compareTo(OrderStatus.PAY) == 0) {
            cancelPayOrder(new ReqIdParam(mallOrder.getId()));
        }


        return HttpResult.ok(true);
    }

    @Override
    public OrderStatisticsVO supplierOrderStatistics(Long userId) {
        return baseMapper.supplierOrderStatistics(userId);
    }

    @Override
    public HttpResult<List<Map<String, Object>>> getOrderIncomeDaily(MallOrder params) {
        List<Map<String, Object>> res = new ArrayList<>();
        Map<String, Object> map = params.getParams();
        try {
            List<String> betweenDays = DateUtils.getBetweenDays(String.valueOf(map.get("beginTime")), String.valueOf(map.get("endTime")));

            if (betweenDays == null) {
                return HttpResult.error();
            }
            for (String day : betweenDays) {
                Map<String, Object> data = new HashMap<>();
                data.put("date", day);
                data.put("num", baseMapper.getOrderIncomeDaily(day, params.getUserId()));
                res.add(data);
            }
            return HttpResult.ok(res);
        } catch (ParseException e) {
            return HttpResult.error("日期解析失败");
        }
    }

    @Override
    public MallOrder getOrderByOrderSn(String orderSn) {
        return lambdaQuery().eq(MallOrder::getOrderSn, orderSn).one();
    }


    /****
     *
     * @param orderVO
     * @param minute   分钟
     */
    private void sendDelayMessageCancelOrder(OrderVO orderVO, long minute) {
        //砍价没有取消订单
        long delayTimes = minute * 1000 * 60;
        //发送延迟消息
        rabbitUtils.sendMessage(orderVO, delayTimes);
    }


    /**
     * 后台首页饼图统计
     *
     * @return 结果
     * @Author lx
     * @Date: 2022/09/23 11:01
     */
    @Override
    public AdminIndexStaticsVO indexStatistics() {
        AdminIndexStaticsVO adminIndexStaticsVo = new AdminIndexStaticsVO();

        // 普通用户数目
        Integer userCount = mallUserService.lambdaQuery().eq(MallUser::getHeadType, UserType.ORDINARY).count();

        adminIndexStaticsVo.setUserCount(userCount != null ? userCount : 0);
        // 初始化参数
        adminIndexStaticsVo.setCutAmount(BigDecimal.ZERO);
        adminIndexStaticsVo.setCutCount(0);
        adminIndexStaticsVo.setKillAmount(BigDecimal.ZERO);
        adminIndexStaticsVo.setKillCount(0);
        adminIndexStaticsVo.setShopAmount(BigDecimal.ZERO);
        adminIndexStaticsVo.setShopCount(0);
        adminIndexStaticsVo.setPtAmount(BigDecimal.ZERO);
        adminIndexStaticsVo.setPtCount(0);

        // 统计订单信息
        List<AdminIndexVo> adminIndexVos = baseMapper.queryIndexStatistics();
        if (adminIndexVos != null && adminIndexVos.size() > 0) {
            for (AdminIndexVo vo : adminIndexVos) {
                if (vo.getOrderType() == OrderType.SHOP) {
                    adminIndexStaticsVo.setShopAmount(vo.getActualPriceTotal() != null ? vo.getActualPriceTotal() : BigDecimal.ZERO);
                    adminIndexStaticsVo.setShopCount(vo.getOrderCount() != null ? vo.getOrderCount() : 0);
                }
                if (vo.getOrderType() == OrderType.STORE) {
                    adminIndexStaticsVo.setShopAmount(vo.getActualPriceTotal() != null ? vo.getActualPriceTotal() : BigDecimal.ZERO);
                    adminIndexStaticsVo.setShopCount(vo.getOrderCount() != null ? vo.getOrderCount() : 0);
                }
            }
        }

        return adminIndexStaticsVo;
    }

    @Override
    public MallAdminOrderStatisticsVO orderStatistics(Long userId, Integer orderMold) {
        LocalDateTime now = LocalDateTime.now();
        MallAdminOrderStatisticsVO vo = new MallAdminOrderStatisticsVO();
        // 根据 type 1|已完成 2|待付款 3|待发货 4|待收货 5|已取消

        // 已完成订单金额
        BigDecimal overMoney = baseMapper.orderStatistics(1, null, userId, orderMold);
        vo.setOverMoney(overMoney);

        // 今日已完成订单金额
        BigDecimal todayOverMoney = baseMapper.orderStatistics(1, now, userId, orderMold);
        vo.setTodayOverMoney(todayOverMoney);

        // 待付款订单金额
        BigDecimal waitPayMoney = baseMapper.orderStatistics(2, null, userId, orderMold);
        vo.setWaitPayMoney(waitPayMoney);

        // 今日待付款订单金额
        BigDecimal todayWaitPayMoney = baseMapper.orderStatistics(2, now, userId, orderMold);
        vo.setTodayWaitPayMoney(todayWaitPayMoney);

        // 待发货订单金额
        BigDecimal waitDeliverMoney = baseMapper.orderStatistics(3, null, userId, orderMold);
        vo.setWaitDeliverMoney(waitDeliverMoney);

        // 今日待发货订单金额
        BigDecimal todayWaitDeliverMoney = baseMapper.orderStatistics(3, now, userId, orderMold);
        vo.setTodayWaitDeliverMoney(todayWaitDeliverMoney);

        // 待收货订单金额
        BigDecimal waitReceiveMoney = baseMapper.orderStatistics(4, null, userId, orderMold);
        vo.setWaitReceiveMoney(waitReceiveMoney);

        // 今日待收货订单金额
        BigDecimal todayWaitReceiveMoney = baseMapper.orderStatistics(4, now, userId, orderMold);
        vo.setTodayWaitReceiveMoney(todayWaitReceiveMoney);

        // 已取消订单金额
        BigDecimal cancelMoney = baseMapper.orderStatistics(5, null, userId, orderMold);
        vo.setCancelMoney(cancelMoney);

        // 今日已取消订单金额
        BigDecimal todayCancelMoney = baseMapper.orderStatistics(5, now, userId, orderMold);
        vo.setTodayCancelMoney(todayCancelMoney);

        if (orderMold != null && orderMold == 4) {
            // 会员订单总金额
            BigDecimal memberMoney = baseMapper.memberStatistics(null, null);
            vo.setMemberMoney(memberMoney);

            // 今日会员订单总金额
            BigDecimal todayMemberMoney = baseMapper.memberStatistics(null, now);
            vo.setTodayMemberMoney(todayMemberMoney);
        }

        return vo;
    }

    @Override
    public MallAdminMemberStatisticsVO memberStatistics() {
        MallAdminMemberStatisticsVO vo = new MallAdminMemberStatisticsVO();
        LocalDateTime now = LocalDateTime.now();

        // 微信支付总金额
        BigDecimal wxPayMoney = baseMapper.memberStatistics(PayType.WX_PAY.getValue(), null);
        vo.setWxPayMoney(wxPayMoney);

        // 今日微信支付总金额
        BigDecimal todayWxPayMoney = baseMapper.memberStatistics(PayType.WX_PAY.getValue(), now);
        vo.setTodayWxPayMoney(todayWxPayMoney);

        // 支付宝支付总金额
        BigDecimal AliPayMoney = baseMapper.memberStatistics(PayType.ALI_PAY.getValue(), null);
        vo.setAliPayMoney(AliPayMoney);

        // 今日支付宝支付总金额
        BigDecimal todayAliPayMoney = baseMapper.memberStatistics(PayType.ALI_PAY.getValue(), now);
        vo.setTodayAliPayMoney(todayAliPayMoney);

        // 余额支付总金额
        BigDecimal balancePayMoney = baseMapper.memberStatistics(PayType.CR_PAY.getValue(), null);
        vo.setBalancePayMoney(balancePayMoney);

        // 今日余额支付总金额
        BigDecimal todayBalancePayMoney = baseMapper.memberStatistics(PayType.CR_PAY.getValue(), now);
        vo.setTodayBalancePayMoney(todayBalancePayMoney);
        return vo;
    }

    @Override
    public HttpResult<ResOrderCountVO> orderCount(LoginUser loginUser) {
        ResOrderCountVO resOrderCount = baseMapper.selectOrderCount(loginUser.getAccountLogin().getUuid());

        return HttpResult.ok(resOrderCount);
    }

    @Override
    public HttpResult<LogisticsVO> logistics(ReqStringParam orderSn) {
        return baseMapper.logistics(orderSn);
    }

    @Override
    public HttpResult<AccumulatedVO> accumulatedRecharge(AccountLogin accountLogin) {
        return baseMapper.accumulatedRecharge(accountLogin.getUuid());
    }

    @Override
    public HttpResult<AccumulatedVO> accumulatedConsumer(AccountLogin accountLogin) {
        return baseMapper.accumulatedConsumer(accountLogin.getUuid());
    }

    @Override
    public IPage<ResOrderGoodsVO> rechargeRecord(IdAndPage idParam, Long uuid) {
        Page<ResOrderGoodsVO> resOrderGoodsIPage = new Page<>(idParam.getPageNum(), idParam.getPageSize());
        return baseMapper.rechargeRecord(resOrderGoodsIPage, idParam.getId(), uuid);
    }

    @Override
    public IPage<MallOrder> rechargeList(Page<MallOrder> page, MallOrder mallOrder) {
        if (mallOrder.getOrderType() != null) {
            mallOrder.setOrderTypeValue(mallOrder.getOrderType().getValue());
        }
        Page<MallOrder> page1 = baseMapper.rechargeList(page, mallOrder);
        page1.getRecords().forEach(item -> {
            item.setOrderTypeDesc(item.getOrderType() != null ? item.getOrderType().getDesc() : "-");
            if (null != item.getPayType()) {
                item.setPayTypeDesc(item.getPayType().getDesc());
            } else {
                item.setPayTypeDesc("-");
            }
        });
        return page1;
    }


    @Override
    public IPage<MallOrder> storeOrderList(Page<MallOrder> page, MallOrder mallOrder) {
        return baseMapper.storeOrderList(page, mallOrder);
    }

    @Override
    public HttpResult<Boolean> verification(ReqIdParam idParam, LoginUser loginCheck) {
        //需要根据核销码查到相关商品是否属于这个店铺
        MallOrderGoods orderGoods = mallOrderGoodsService.lambdaQuery()
                .eq(MallOrderGoods::getOrderGoodsSn, idParam.getOrderGoodsId())
                .eq(MallOrderGoods::getVerificationCode, idParam.getVerificationCode())
                .one();
        if (orderGoods != null) {
            //根据订单状态判断核销码是否已经使用
            if (orderGoods.getOrderStatus().equals(OrderStatus.OK) || orderGoods.getOrderStatus().equals(OrderStatus.DAI_CENTXT)) {
                return HttpResult.error("核销码已核销！");
            }
            //根据商品id查到相关店铺
            MallGoods mallGoods = mallGoodsService.lambdaQuery().eq(MallGoods::getId, orderGoods.getGoodsId()).one();
            if (mallGoods.getStoreId().equals(idParam.getStoreId())) {
                orderGoods.setOrderStatus(OrderStatus.DAI_CENTXT);
                orderGoods.setConfirmTime(LocalDateTime.now());
                if (orderGoods.getOrderType().equals(OrderType.STORE)) {
                    mallMessageInformService.addOrderMessage("您的商品已核销成功", orderGoods.getId(), orderGoods.getUuid());
                }
                //待结算货款
                handleData(orderGoods);
                return HttpResult.ok(mallOrderGoodsService.updateById(orderGoods));
            } else {
                return HttpResult.error("不是该店铺商品！");
            }
        } else {
            return HttpResult.error("核销码错误！");
        }

    }

    @Override
    public HttpResult<Boolean> check(MallOrder mallOrder) {
        //需要根据核销码查到相关商品是否属于这个店铺
        MallOrderGoods orderGoods = mallOrderGoodsService.lambdaQuery()
                .eq(MallOrderGoods::getOrderGoodsSn, mallOrder.getOrderGoodsSn())
                .eq(MallOrderGoods::getVerificationCode, mallOrder.getVerificationCode())
                .one();
        if (orderGoods != null) {
            //根据订单状态判断核销码是否已经使用
            if (orderGoods.getOrderStatus().equals(OrderStatus.OK) || orderGoods.getOrderStatus().equals(OrderStatus.DAI_CENTXT)) {
                return HttpResult.error("核销码重复使用！");
            }
//            MallOrder order = baseMapper.selectBy

            //根据商品id查到相关店铺
            MallGoods mallGoods = mallGoodsService.lambdaQuery().eq(MallGoods::getId, orderGoods.getGoodsId()).one();
            if (mallGoods.getStoreId().equals(mallOrder.getStoreId()) || mallOrder.getUserId() == 1L || mallOrder.getUserId() == 2L) {
                orderGoods.setOrderStatus(OrderStatus.DAI_CENTXT);
                orderGoods.setConfirmTime(LocalDateTime.now());
                if (orderGoods.getOrderType().equals(OrderType.STORE)) {
                    mallMessageInformService.addOrderMessage("您的商品已核销成功", orderGoods.getId(), orderGoods.getUuid());
                }
                //待结算货款
                handleData(orderGoods);
                return HttpResult.ok(mallOrderGoodsService.updateById(orderGoods));
            } else {
                return HttpResult.error("不是该店铺商品！");
            }
        } else {
            return HttpResult.error("核销码错误！");
        }
    }


    @Override
    public MallAdminOrderStatisticsVO orderStatistics1(Long userId, ReqIdParam idParam) {
        return baseMapper.orderStatistics1(userId, idParam);
    }

    @Override
    public HttpResult<ResOrderMallSubmitVO> submitOffline(MallOrder mallOrder) {
        MallUser user = mallUserService.lambdaQuery().eq(MallUser::getUuid, mallOrder.getUuid()).one();
        MallStore mallStore = mallStoreService.lambdaQuery().eq(MallStore::getId, mallOrder.getStoreId()).one();

        mallOrder.setEndTime(LocalDateTime.now().plusMinutes(10));
        mallOrder.setMobile(user.getMobile());
        mallOrder.setPicUrl(mallStore.getPhoto());
        mallOrder.setGoodsPrice(mallOrder.getActualPrice());
        save(mallOrder);

        MallOrderGoods mallOrderGoods = new MallOrderGoods();

        BeanUtils.copyProperties(mallOrder, mallOrderGoods);
        mallOrderGoods.setOrderGoodsSn(mallOrder.getOrderSn() + "-1");
        mallOrderGoods.setMobile(user.getMobile());

        mallOrderGoods.setRemark(mallOrder.getMessage());
        mallOrderGoods.setPicUrl(mallStore.getPhoto());
        mallOrderGoods.setPayPrice(mallOrder.getActualPrice());
        mallOrderGoods.setPrice(mallOrder.getActualPrice());
        mallOrderGoods.setUuid(user.getUuid());
        mallOrderGoods.setOrderSn(mallOrder.getOrderSn());
        mallOrderGoods.setGoodsName("店铺扫码支付");
        mallOrderGoods.setNumber(1);
        mallOrderGoods.setVerificationOrder(1);
        mallOrderGoods.setOrderType(mallOrder.getOrderType());
        mallOrderGoods.setOrderStatus(mallOrder.getOrderStatus());
        mallOrderGoods.setGoodsId(0L);
        mallOrderGoods.setNormsId(0L);
        mallOrderGoods.setCreateTime(LocalDateTime.now());
        mallOrderGoodsService.save(mallOrderGoods);
        return HttpResult.ok(new ResOrderMallSubmitVO(mallOrder.getOrderSn(), mallOrder.getActualPrice()));
    }

    @Override
    public MallAdminOrderStatisticsVO rechargeOrderStatistics(Long userId, ReqIdParam idParam) {
        return baseMapper.rechargeOrderStatistics(userId, idParam);
    }

    @Override
    public MallAdminOrderStatisticsVO supplierOrder(Long userId, ReqIdParam idParam) {
        SysUser sysUser = sysUserService.selectUserById(userId);
        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getMobile, sysUser.getPhonenumber()).one();
        MallAdminOrderStatisticsVO mallAdminOrderStatisticsVO = baseMapper.supplierOrder(one.getUuid(), idParam);

        BigDecimal withdrawMoney = supplierWithdrawAuditService.value(one.getUuid());
        mallAdminOrderStatisticsVO.setWithdrawMoney(withdrawMoney == null ? BigDecimal.ZERO : withdrawMoney);

        return mallAdminOrderStatisticsVO;
    }

    @Override
    public MallAdminOrderStatisticsVO storeOrder(Long userId, ReqIdParam idParam) {
        SysUser sysUser = sysUserService.selectUserById(userId);
        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getMobile, sysUser.getPhonenumber()).one();
        MallAdminOrderStatisticsVO mallAdminOrderStatisticsVO = baseMapper.storeOrder(one.getUuid(), idParam);
        BigDecimal withdrawMoney = storeWithdrawAuditService.value(one.getUuid());
        mallAdminOrderStatisticsVO.setWithdrawMoney(withdrawMoney == null ? BigDecimal.ZERO : withdrawMoney);

        return mallAdminOrderStatisticsVO;
    }

    @Override
    public MallAdminOrderStatisticsVO storeOrderStatistics(Long userId, ReqIdParam idParam) {
        return baseMapper.storeOrderStatistics(userId, idParam);
    }

    @Override
    public TotalOrderStatisticsVO exportOrderStatisticsVO() {
        TotalOrderStatisticsVO totalOrderStatisticsVO = new TotalOrderStatisticsVO();

        MathContext mathContext = new MathContext(2);

        //消费券充值总金额
        BigDecimal rechargeAmount = balanceChangeService.rechargeAmount();

        //实体店消费券核销统计
        BigDecimal storeConsumeRoll = baseMapper.storeOrderTotalAmount();

        //自营商城消费券核销统计
        BigDecimal shopConsumeRoll = baseMapper.shopConsumeRoll();

        //消费券已使用总额计算  //是个负数
        BigDecimal useTotalConsumeRoll = balanceChangeService.useTotalConsumeRoll();

        //未核销消费券统计明细
        BigDecimal waitConsumeRoll = rechargeAmount.subtract((storeConsumeRoll.add(shopConsumeRoll))).setScale(2, RoundingMode.HALF_UP);

        //消费券核销账户  消费券充值总金额*50%
        BigDecimal verificationConsumeRoll = rechargeAmount.multiply(new BigDecimal("0.50")).setScale(2, RoundingMode.HALF_UP);

        //提货单核销账户  消费券充值总金额*35%
        BigDecimal verificationGoodsRoll = rechargeAmount.multiply(new BigDecimal("0.35")).setScale(2, RoundingMode.HALF_UP);

        //公司管理费收益账户  消费券充值总金额*1%
        BigDecimal management = rechargeAmount.multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP);

        //保证金账户  消费券充值总金额*10%
        BigDecimal earnestMoney = rechargeAmount.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP);

        //运营账户  消费券充值总金额*4%
        BigDecimal operator = rechargeAmount.multiply(new BigDecimal("0.04")).setScale(2, RoundingMode.HALF_UP);

        //消费券已使用总额：{实体店消费劵核销统计+自营商城消费劵核销统计}
        BigDecimal useConsumeRoll = storeConsumeRoll.add(shopConsumeRoll).setScale(2, RoundingMode.HALF_UP);

        //实体店：实体店消费劵核销统计*50%
        BigDecimal storeTotal = storeConsumeRoll.multiply(new BigDecimal("0.50")).setScale(2, RoundingMode.HALF_UP);

        //自营商城：自营商城消费劵核销统计*30%
        BigDecimal shopTotal = shopConsumeRoll.multiply(new BigDecimal("0.30")).setScale(2, RoundingMode.HALF_UP);

        //消费券现金余额：{消费券已使用总额*50%}-{实体店+自营商城}
//        BigDecimal cash = useConsumeRoll.multiply(new BigDecimal("0.50")).subtract((storeTotal.add(shopTotal))).setScale(2, RoundingMode.HALF_UP);
        BigDecimal cash = (storeTotal.add(shopTotal)).setScale(2, RoundingMode.HALF_UP);

        //提货单未核销总额
        BigDecimal waitGoodsRoll = mallUserService.waitGoodsRoll();

        //提货单已核销总额
        BigDecimal goodsRoll = mallUserService.goodsRoll();

        //{提货单赠送总额}={提货单未核销总额+提货单已核销总额}
        BigDecimal presentsGoodsRoll = waitGoodsRoll.add(goodsRoll).setScale(2, RoundingMode.HALF_UP);


        totalOrderStatisticsVO.setRechargeAmount(rechargeAmount);
        totalOrderStatisticsVO.setStoreConsumeRoll(storeConsumeRoll);
        totalOrderStatisticsVO.setShopConsumeRoll(shopConsumeRoll);
        totalOrderStatisticsVO.setWaitConsumeRoll(waitConsumeRoll);
        totalOrderStatisticsVO.setVerificationConsumeRoll(verificationConsumeRoll);
        totalOrderStatisticsVO.setVerificationGoodsRoll(verificationGoodsRoll);
        totalOrderStatisticsVO.setManagement(management);
        totalOrderStatisticsVO.setEarnestMoney(earnestMoney);
        totalOrderStatisticsVO.setOperator(operator);
        totalOrderStatisticsVO.setUseConsumeRoll(useConsumeRoll);
        totalOrderStatisticsVO.setUseTotalConsumeRoll(useTotalConsumeRoll.abs());
        totalOrderStatisticsVO.setStoreTotal(storeTotal);
        totalOrderStatisticsVO.setShopTotal(shopTotal);
        totalOrderStatisticsVO.setCash(cash);
        totalOrderStatisticsVO.setPresentsGoodsRoll(presentsGoodsRoll);
        totalOrderStatisticsVO.setWaitGoodsRoll(waitGoodsRoll);
        totalOrderStatisticsVO.setGoodsRoll(goodsRoll);
        return totalOrderStatisticsVO;
    }
}
